document.addEventListener('DOMContentLoaded', function () {
    let viewCaseListeners = [];
    let cancelApplicationListeners = [];
    let currentModal = null;


    function getQueryParameter(datatype) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(datatype);
    }

    doctorName = getQueryParameter('name')
    doctorInfo = {
        doctor_name: doctorName
    }

    

    //此处从后端获取信息
    const data = [
        { caseID: '1', patient: 'bbb', bedId: 'YK.101', department: '眼科', doctor: 'ccc', location: '3F', status: '未处理' },
        { caseID: '2', patient: 'bbb', bedId: 'YK.102', department: '眼科', doctor: 'ccc', location: '3F', status: '未处理' },
    ];

    const tableBody = document.querySelector('.sectionForm > tbody');
    if (!tableBody) {
        // 如果不存在tbody，则创建一个新的tbody
        const tbody = document.createElement('tbody');
        document.querySelector('.sectionForm').appendChild(tbody);
    } else {
        tableBody.innerHTML = ''; // 清空已有的tbody内容
    }

    data.forEach(item => {
        const row = document.createElement('tr');
        row.classList.add('mt-33');

        //获取当前病人和床位id，用于后续区分
        current_id = item.caseID

        Object.values(item).forEach(value => {
            const cell = document.createElement('td');
            cell.classList.add('font', 'text_3');
            cell.textContent = value;
            row.appendChild(cell);
        });

        const operationCell = document.createElement('td');
        operationCell.classList.add('font', 'text_3', 'shrink-0', 'ml-121');

        const viewCaseButton = createButton(current_id + '_case', '查看病例');

        const cancelApplicationButton = createButton(current_id + '_cancelApplicationBtn', '取消申请', true);

        operationCell.appendChild(viewCaseButton);
        operationCell.appendChild(cancelApplicationButton);

        row.appendChild(operationCell);
        tableBody.appendChild(row);

        // 绑定事件监听器
        viewCaseButton.addEventListener('click', function () {
            case_id = (viewCaseButton.id).split("_")[0];

            //获取病例信息
            case_info = {
                caseID: case_id
            }
            //json = 

            if (!currentModal) {
                showPatientInformation(json);
            }
        });

        cancelApplicationButton.addEventListener('click', function () {

            case_id = (viewCaseButton.id).split("_")[0];

            showHideModal('取消', case_id);
        });

        // Store the listeners for later removal
        viewCaseListeners.push(viewCaseButton);
        cancelApplicationListeners.push(cancelApplicationButton);
    });

    // Function to remove old event listeners when DOMContentLoaded fires again
    function removeOldEventListeners() {
        viewCaseListeners.forEach(button => {
            button.removeEventListener('click', showPatientInformation);
        });
        cancelApplicationListeners.forEach(button => {
            button.removeEventListener('click', showHideModal);
        });
    }

    // Remove old event listeners before adding new ones
    removeOldEventListeners();
});




// 显示/隐藏模态框
function showHideModal(action, case_id) {
    var approvalContainer = document.createElement('div');
    approvalContainer.id = action == '取消' ? 'approve' : 'reject';
    approvalContainer.className = 'modal-container';
    approvalContainer.style.textAlign = 'left';

    // 创建modal-content div  
    var modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.style.display = 'block';

    var approvalHead = document.createElement('h2');
    approvalHead.id = 'patient-head';
    approvalHead.style.textAlign = 'center';
    approvalHead.textContent = '提示信息';

    var action_message = modal_div_creator(action, 'error_information', `您确定要${action}吗？`);
    var approve = modal_button_creator('approve-button', '确认')
    var cancel = modal_button_creator('cancel-button', '取消')

    modalContent.appendChild(approvalHead)
    modalContent.appendChild(action_message)
    modalContent.appendChild(approve)
    modalContent.appendChild(cancel)

    // 给确定按钮添加点击事件监听器  
    approve.addEventListener('click', function () {
        if (approvalContainer.id == 'approve') {
            requestLine = document.getElementById(case_id + '_cancelApplicationBtn').parentNode.parentNode;
            if (requestLine.parentNode)
                requestLine.parentNode.removeChild(requestLine)

            //取消请求相关代码
            request_info = {
                caseID: case_id
            }
            console.log(request_info)

            //result = 
            //display_alert_information(result.message)
        }

        if (approvalContainer.parentNode) {
            approvalContainer.parentNode.removeChild(approvalContainer);
        }

    });


    // 给取消按钮添加点击事件监听器  
    cancel.addEventListener('click', function () {
        if (approvalContainer.parentNode) {
            approvalContainer.parentNode.removeChild(approvalContainer);
        }
    });

    approvalContainer.appendChild(modalContent);

    document.body.appendChild(approvalContainer);
}



function showPatientInformation(json) {

    //根据床位号获取病人信息

    var patientContainer = document.createElement('div');
    patientContainer.id = 'patient-container';
    patientContainer.className = 'modal-container';
    patientContainer.style.textAlign = 'left';

    // 创建modal-content div  
    var modalContent = document.createElement('div');
    modalContent.className = 'modal-content';
    modalContent.style.display = 'block';

    var patientHead = document.createElement('h2');
    patientHead.id = 'patient-head';
    patientHead.style.textAlign = 'center';
    patientHead.textContent = '病人信息';

    var chargerName = modal_div_creator('charger-name', 'bed_card_information', '病床管理者姓名: ' + json.charge_doctor_id);
    var chargerID = modal_div_creator('charger-id', 'bed_card_information', '病床管理者ID: ' + json.charge_doctor_name);
    var patientName = modal_div_creator('patient-name', 'bed_card_information', '病人姓名: ' + json.patient_info.patient_name);
    var patientID = modal_div_creator('patient-id', 'bed_card_information', '病人ID: ' + json.patient_info.patient_id);
    var patientGender = modal_div_creator('patient-gender', 'bed_card_information', '病人性别: ' + json.patient_info.gender);
    var patientAge = modal_div_creator('patient-age', 'bed_card_information', '病人年龄: ' + json.patient_info.age);
    var doctorName = modal_div_creator('doctor-name', 'bed_card_information', '医生姓名: ' + json.patient_info.doctor_name);
    var doctorID = modal_div_creator('doctor-id', 'bed_card_information', '医生ID: ' + json.patient_info.doctor_id);
    var description = modal_div_creator('description', 'bed_card_information', '病例描述: ' + json.patient_info.description);
    var cancel = modal_button_creator('cancel-button', '取消')

    modalContent.appendChild(patientHead);
    modalContent.appendChild(chargerName);
    modalContent.appendChild(chargerID);
    modalContent.appendChild(patientName);
    modalContent.appendChild(patientID);
    modalContent.appendChild(patientGender);
    modalContent.appendChild(patientAge);
    modalContent.appendChild(doctorName);
    modalContent.appendChild(doctorID);
    modalContent.appendChild(doctorName);
    modalContent.appendChild(description);
    modalContent.appendChild(cancel)

    // 给取消按钮添加点击事件监听器  
    cancel.addEventListener('click', function () {
        // 从 DOM 中移除 patientContainer  
        if (patientContainer.parentNode) {
            patientContainer.parentNode.removeChild(patientContainer);
        }
    });

    patientContainer.appendChild(modalContent);

    document.body.appendChild(patientContainer);
}



function createButton(id, text, isSecondary = false) {
    const button = document.createElement('button');
    button.id = id;
    button.className = `justify-start items-center ${isSecondary ? 'text-wrapper_1' : 'text-wrapper'}`;
    const span = document.createElement('span');
    span.className = 'font_3 text_3';
    span.textContent = text;
    button.appendChild(span);

    return button;
}

// 创建查看病例的模态框
function createCaseModal(caseInfo) {
    const modalContent = `
        <div class="modal-content">
            <h2 class="modal-title">病例详情</h2>
            <div class="case-info">
                <p><strong>病例ID：</strong>${caseInfo.case_id}</p>
                <p><strong>患者姓名：</strong>${caseInfo.patient_name}</p>
                <p><strong>患者ID：</strong>${caseInfo.patient_id}</p>
                <p><strong>主治医生：</strong>${caseInfo.doctor_name}</p>
                <p><strong>科室：</strong>${caseInfo.dept_name}</p>
                <p><strong>病情描述：</strong>${caseInfo.description}</p>
                <p><strong>预计住院天数：</strong>${caseInfo.predict_days}</p>
            </div>
            <div class="modal-buttons">
                <button onclick="closeModal()" class="modal-btn">关闭</button>
            </div>
        </div>
    `;
    
    const modalContainer = document.createElement('div');
    modalContainer.className = 'modal-container';
    modalContainer.innerHTML = modalContent;
    document.body.appendChild(modalContainer);
}

// 查看病例按钮点击事件处理
function viewCase(caseId) {
    fetch(`/api/case/${caseId}`)
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                createCaseModal(data.case_info);
            } else {
                alert('获取病例信息失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取病例信息失败');
        });
}

// 关闭模态框
function closeModal() {
    const modalContainer = document.querySelector('.modal-container');
    if (modalContainer) {
        modalContainer.remove();
    }
}

// 初始化表格数据
document.addEventListener('DOMContentLoaded', function() {
    const tableBody = document.querySelector('tbody');
    
    // 获取请求列表数据
    fetch('/api/requests/my')
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                data.requests.forEach(request => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${request.case_id}</td>
                        <td>${request.patient_name}</td>
                        <td>${request.bed_id}</td>
                        <td>${request.dept_name}</td>
                        <td>${request.doctor_name}</td>
                        <td>${request.location}</td>
                        <td>${getStatusText(request.request_status)}</td>
                        <td>
                            <button onclick="viewCase('${request.case_id}')" class="view-btn">查看病例</button>
                            ${request.request_status === 0 ? 
                                `<button onclick="cancelRequest('${request.request_id}')" class="cancel-btn">取消申请</button>` 
                                : ''}
                        </td>
                    `;
                    tableBody.appendChild(row);
                });
            } else {
                alert('获取请求列表失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('获取请求列表失败');
        });
});

// 获取状态文本
function getStatusText(status) {
    const statusMap = {
        0: '待处理',
        1: '已通过',
        2: '已拒绝',
        3: '已取消'
    };
    return statusMap[status] || '未知状态';
}

// 取消申请
function cancelRequest(requestId) {
    if (confirm('确定要取消这个申请吗？')) {
        fetch(`/api/request/${requestId}/cancel`, {
            method: 'POST'
        })
        .then(response => response.json())
        .then(data => {
            if (data.msg === 'success') {
                alert('申请已取消');
                location.reload();
            } else {
                alert('取消申请失败：' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('取消申请失败');
        });
    }
}